package com.puboot.module.admin.media;

import com.puboot.common.util.FileTools;
import com.puboot.module.admin.model.BizFile;
import com.puboot.module.admin.service.BizFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;

/**
 * @Description
 * @Author 申紫微
 * @Data 2020-02-14 14:57:24
 * @Version 1.0
 */
@Controller
@Scope("prototype")
@Slf4j
public class DownloadAction extends BaseAction{

    @Autowired
    BizFileService fileService;

    @Value(value = "${mediaDomain}")
    private String mediaDomain;

    @RequestMapping("/file/{fid}")
    public void file(@PathVariable String fid){
        this.downloadFile(fid,() -> {
            // not do anything
        }, (dbFile, file) -> {
           response.sendRedirect(mediaDomain.concat(dbFile.getFileAddr()));
        });
    }

    /**
     * @Author 申紫微
     * @Description 下载文件
     * @Date 15:35 2020/2/14
     * @Param [fid, notExistOption, existOption]
     * @return void
     **/
    private void downloadFile(String fid, FileNotExistOption notExistOption, FileExistOption existOption){

        log.debug("fid:{}",fid);
        //设置页面不缓存
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);

        BizFile dbFile = fileService.selectByFileId(fid);
        if(Objects.isNull(dbFile) || dbFile.getStatus() < 0){
            try {
                notExistOption.execute();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            return;
        }
        log.debug("fid:{}",fid);
        FileInputStream fis = null;
        try {
            File img = new File(mediaDomain.concat(dbFile.getFileAddr()));
            if (Objects.isNull(img)&& !img.exists()) {
                notExistOption.execute();
            }else{
                existOption.execute(dbFile, img);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            FileTools.close(fis);
        }
    }

}
